﻿#include "tcpserver.h"

TcpServer::TcpServer(uint16_t port, const std::string& ip)
    : m_port(port)
    , m_acceptor(&m_baseloop, port, ip)
    , m_timeout(10)
    , m_enableInactiveRelease(false)
    , m_cid(0)
    , m_pool(&m_baseloop)
{}

TcpServer::~TcpServer() {

}

/*_serverCloseCb, 从_conns中移除*/
void TcpServer::_handleSvrClose(const ConnectionPtr& cptr)
{
    int id = cptr->getConnId();
    auto it = m_conns.find(id);
    if(it != m_conns.end())
    {
        m_conns.erase(it);
    }
}
void TcpServer::handleSvrClose(const ConnectionPtr& cptr)
{
    m_baseloop.runInLoop(std::bind(&TcpServer::_handleSvrClose, this, cptr));
}

void TcpServer::newConnection(int newfd)
{
    m_cid++;
    ConnectionPtr con(new Connection(m_pool.nextLoop(), m_cid, newfd));
    con->setConnectCallback(m_connectCallback);
    con->setMessageCallback(m_messageCallback);
    con->setAnyCallback(m_anyCallback);
    con->setCloseCallback(m_closeCallback);
    con->setServerCloseCallback(std::bind(&TcpServer::handleSvrClose, this, std::placeholders::_1));
    if (m_enableInactiveRelease)
    {    
        con->enableInactiveRelease(m_timeout);
    }
    con->establishConnection();
    m_conns.insert(std::make_pair(m_cid, con));
}

void TcpServer::_addTimerTask(const TaskFunc_t &task, int timeout)
{
    m_cid++;
    m_baseloop.addTimerTask(m_cid, timeout, task);
}

void TcpServer::addTimerTask(const TaskFunc_t &task, int timeout)
{
    m_baseloop.runInLoop(std::bind(&TcpServer::_addTimerTask, this, task, timeout));
}

void TcpServer::enableInactiveRelease(int timeout)
{
    m_timeout = timeout;
    m_enableInactiveRelease = true;
}

void TcpServer::setThreadCount(int threadCount)
{
    m_pool.setThreadCount(threadCount);
}

void TcpServer::start() 
{
    m_pool.create();
    m_acceptor.setNewConnectionCallback(std::bind(&TcpServer::newConnection, this, std::placeholders::_1));
    m_acceptor.listen();
    return m_baseloop.start();
}
//设置连接的回调函数
void TcpServer::setConnectCallback(const ConnectCallback &cb)
{
    m_connectCallback = cb;
}
void TcpServer::setMessageCallback(const MessageCallback &cb)
{
    m_messageCallback = cb;
}
void TcpServer::setCloseCallback(const CloseCallback &cb)
{
    m_closeCallback = cb;
}
void TcpServer::setAnyCallback(const AnyCallback &cb)
{
    m_anyCallback = cb;
}
